<template>
    <el-menu class="aside-menu" :collapse="collapse" :collapse-transition="false" :default-active="activeMenu" :unique-opened="false" router @select="onMenuSelect">
        <template v-for="item in menuList" :key="item.id">
            <component :is="renderMenu(item)" />
        </template>
    </el-menu>
</template>

<script setup lang="ts">
import { ref, onMounted, inject, h, watch } from "vue";
import { useRoute } from "vue-router";
import { ElSubMenu, ElMenuItem } from "element-plus";
import LemonIcon from "@/components/LemonIcon.vue";

// 获取路由实例
const route = useRoute();

//获取自定义全局方法
const { http, authStore, emitter } = inject<any>("method");

//是否展开
const collapse = ref<boolean>(authStore.menuCollapse);
emitter.on("on-menu-collapse", (val: boolean) => (collapse.value = val));

//当前激活的菜单
const activeMenu = ref<string>("");

//定义菜单项类型
interface MenuItem {
    id: string;
    name: string;
    icon?: string;
    uri?: string;
    treeLinkId?: string;
    bread?: string[];
    children?: MenuItem[];
}

// 菜单列表
const menuList = ref<MenuItem[]>([]);

// 计算当前激活的菜单
const computeActiveMenu = () => {
    const currentPath = route.path;

    // 在菜单列表中查找匹配的路由
    const findActiveMenu = (menus: MenuItem[]): string | undefined => {
        for (const menu of menus) {
            if (menu.uri === currentPath) {
                return menu.treeLinkId || menu.id;
            }
            if (menu.children && menu.children.length > 0) {
                const childActive = findActiveMenu(menu.children);
                if (childActive) return childActive;
            }
        }
        return undefined;
    };

    const activeId = findActiveMenu(menuList.value);
    if (activeId) {
        activeMenu.value = activeId;
    } else {
        // 如果没有找到匹配的菜单，尝试使用路由路径作为fallback
        activeMenu.value = currentPath;
    }
};

//监听路由变化
watch(
    () => route.path,
    (_newPath) => {
        computeActiveMenu();
    }
);

//监听菜单列表变化
watch(menuList, (newMenus) => {
    if (newMenus.length > 0) {
        computeActiveMenu();
    }
});

//加载菜单列表
const getAsideMenu = async () => {
    menuList.value = await http.get(`/getAsideMenu`);
    //设置面包屑
    authStore.setBreadcrumbList(getBreadcrumb(menuList.value));

    // 菜单加载完成后计算激活状态
    computeActiveMenu();
};

// 菜单选择处理
const onMenuSelect = (index: string, _indexPath: string[]) => {
    activeMenu.value = index;

    // 查找对应的菜单项
    const findMenuByIndex = (menus: MenuItem[], targetIndex: string): MenuItem | undefined => {
        for (const menu of menus) {
            if (menu.treeLinkId === targetIndex || menu.id === targetIndex) {
                return menu;
            }
            if (menu.children && menu.children.length > 0) {
                const found = findMenuByIndex(menu.children, targetIndex);
                if (found) return found;
            }
        }
        return undefined;
    };

    const selectedMenu = findMenuByIndex(menuList.value, index);
    if (selectedMenu && selectedMenu.uri) {
        emitter.emit("router-push", selectedMenu.uri);
    }
};

const renderMenu = (menu: MenuItem) => {
    if (menu?.children && menu?.children?.length) {
        return h(
            ElSubMenu,
            {
                index: menu.treeLinkId || menu.id,
                key: menu.id,
            },
            {
                title: () => [h(LemonIcon, { icon: menu.icon, value: menu.name })],
                default: () => menu.children?.map((child: MenuItem) => renderMenu(child)),
            }
        );
    } else {
        return h(
            ElMenuItem,
            {
                index: menu.treeLinkId || menu.id,
                key: menu.id,
            },
            {
                title: () => [h(LemonIcon, { icon: menu.icon, value: menu.name })],
            }
        );
    }
};

// 定义面包屑类型
interface Bread {
    route?: string;
    bread?: string[];
}

//递归获取路由和面包屑
const getBreadcrumb = (menus: MenuItem[]): Bread[] => {
    let breads: Bread[] = [];
    for (let i = 0; i < menus.length; i++) {
        const menu = menus[i];
        if (menu.uri && menu.bread && menu.bread.length) {
            breads.push({ route: menu.uri, bread: menu.bread });
        }
        if (menu.children && menu.children.length > 0) {
            breads = [...breads, ...getBreadcrumb(menu.children)];
        }
    }
    return breads;
};

//挂载时执行
onMounted(() => {
    getAsideMenu();
    // 初始计算激活状态
    computeActiveMenu();
});
</script>

<style scoped lang="less">
.aside-menu {
    height: 100%;
    overflow-x: hidden;
    overflow-y: auto;
    scrollbar-width: none;

    // 隐藏滚动条但保持滚动功能
    &::-webkit-scrollbar {
        width: 0;
        height: 0;
    }

    :deep(.el-menu-item),
    :deep(.el-sub-menu__title) {
        span {
            font-weight: bold;
        }
    }

    // 激活菜单项样式
    :deep(.el-menu-item.is-active) {
        background-color: var(--el-color-primary-light-9);
        color: var(--el-color-primary);

        &:before {
            content: "";
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 16px;
            background-color: var(--el-color-primary);
            border-radius: 0 2px 2px 0;
        }
    }
}
</style>
